package com.FFmpeg;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.TimeUnit;

/**
 * @author 航
 * @date 2024/07/08 16:02
 **/
public class VideoInfo {

    private static final Logger logger = LogManager.getLogger(VideoInfo.class);

    /**
     * 获取文件扩展名
     */
    public static String getExtensionName(String filename) {
        if ((filename != null) && (!filename.isEmpty())) {
            int dot = filename.lastIndexOf('.');
            if ((dot >-1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }


    /**
     * 获得该视频文件的时长，返回一个字符串
     * @param path
     * @param fileName
     * @return “00:04:51.41”
     * @throws Exception
     */
    public String findDuration(String path,String fileName) throws Exception{
        // 视频文件路径
        String videoFilePath = path + "\\" + fileName;
        // FFmpeg 命令获取视频时长
        String command = "ffmpeg -i " + videoFilePath + " 2>&1";

        try {
            // 执行命令
            Process process = Runtime.getRuntime().exec(command);

            // 读取命令行输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String line;
            String duration = null;

            while ((line = reader.readLine()) != null) {
                // 查找时长信息
                if (line.contains("Duration:")) {
                    duration = line.split("Duration: ")[1].split(",")[0].trim();
                    break;
                }
            }

            process.waitFor(5, TimeUnit.SECONDS);  // 等待进程结束

            // 输出结果
            if (duration != null) {
                logger.info("File Name: {}", fileName);
                logger.info("Duration: {}", duration);
            } else {
                logger.info("Could not retrieve video duration.");
            }
            return duration;

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        throw new Exception("no found");
    }
}
